package org.framework.lazy.cloud.network.heartbeat.client.netty.permeate.udp.filter;

import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.nio.NioDatagramChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.timeout.IdleStateHandler;
import org.framework.lazy.cloud.network.heartbeat.client.netty.permeate.udp.handler.NettyUdpClientHandler;
import org.framework.lazy.cloud.network.heartbeat.client.netty.permeate.udp.socket.NettyUdpClientSocket;
import org.framework.lazy.cloud.network.heartbeat.common.adapter.ChannelTypeAdapter;
import org.framework.lazy.cloud.network.heartbeat.common.decoder.NettyProxyMsgDecoder;
import org.framework.lazy.cloud.network.heartbeat.common.encoder.NettyProxyMsgEncoder;
import org.framework.lazy.cloud.network.heartbeat.common.filter.DebugChannelInitializer;

public class NettyUdpClientFilter extends DebugChannelInitializer<NioDatagramChannel> {


    private final ChannelTypeAdapter channelTypeAdapter;
    private final NettyUdpClientSocket nettyUdpClientSocket;

    public NettyUdpClientFilter(ChannelTypeAdapter channelTypeAdapter, NettyUdpClientSocket nettyUdpClientSocket) {
        this.channelTypeAdapter = channelTypeAdapter;
        this.nettyUdpClientSocket = nettyUdpClientSocket;
    }

    @Override
    protected void initChannel0(NioDatagramChannel ch) throws Exception {
        ChannelPipeline pipeline = ch.pipeline();

        /* * 解码和编码，应和服务端一致 * */
//        pipeline.addLast(new NettyMsgDecoder(Integer.MAX_VALUE, 0, 4, -4, 0));
//        pipeline.addLast(new NettMsgEncoder());
        // 解码、编码
        pipeline.addLast(new NettyProxyMsgDecoder(Integer.MAX_VALUE, 0, 4, -4, 0));
        pipeline.addLast(new NettyProxyMsgEncoder());
// pipeline.addLast("framer", new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
        //入参说明: 读超时时间、写超时时间、所有类型的超时时间、时间格式
        //因为服务端设置的超时时间是5秒，所以设置4秒

        pipeline.addLast(new IdleStateHandler(0, 4, 0));
        pipeline.addLast("decoder", new StringDecoder());
        pipeline.addLast("encoder", new StringEncoder());
        pipeline.addLast("doHandler", new NettyUdpClientHandler(channelTypeAdapter, nettyUdpClientSocket)); //客户端的逻辑
    }
}